#include "Http.hpp"
#include "TcpServer.hpp" // 网络通信
#include <memory>

void Usage(std::string proc)
{
    std::cerr << "Usage: " << proc << " localport" << std::endl;
}

// std::string TestHttp(std::string &reqstr)

// {
//     std::cout << "################" << std::endl;
//     std::cout << reqstr << std::endl;
//     std::cout << "################" << std::endl;

//     std::string response = "HTTP/1.1 200 OK\r\n\r\n";
//     response +=  R"(<!DOCTYPE html>
//     <html lang="en">
//     <head>
//         <meta charset="UTF-8">
//         <meta name="viewport" content="width=device-width, initial-scale=1.0">
//         <title>Hello World</title>
//     </head>
//     <body>
//         <h1>Hello World</h1>
//     </body>
//     </html>)";

//     return response;
// }

HttpResponse Login(HttpRequest &req)
{
    // test Cookie 
    HttpResponse resp;
    // resp.SetCode(200);
    resp.SetCode(301);
    // resp.SetHeader("Set-Cookie", req.Body());
    resp.SetCookie("Set-Cookie", "k=1");
    resp.SetHeader("Location", "/");
    LOG(LogLevel::DEBUG) << "------Login " << req.Body();

    return resp;
}

HttpResponse Register(HttpRequest &req)
{
    LOG(LogLevel::DEBUG) << "------Register " << req.Body();
    
}

HttpResponse Search(HttpRequest &req)
{
    LOG(LogLevel::DEBUG) << "------Search " << req.Body();
    
}

int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        Usage(argv[0]);
        exit(0);
    }

    Console();
    // HTTP协议
    std::unique_ptr<Http> http = std::make_unique<Http>();
    // 微服务接口
    http->Register("/login", Login);
    http->Register("/register", Register);
    http->Register("/search", Search);

    // 网络通信模块
    uint16_t serverport = std::stoi(argv[1]);
    // 创建tcp套接字
    std::unique_ptr<TcpServer> tcp = std::make_unique<TcpServer>(serverport, 
        [&http](std::string &reqstr)->std::string
        {
            return http->Hanlerrequst(reqstr);
        }
    );
    tcp->Run();

    return 0;
}